<template>
  <div class="app-container">
    <el-row :gutter="12">
      <el-col :span="5">
        <el-card  style="height: 650px;">
          <div slot="header" class="clearfix">
            <span>工序列表</span>
            <div style="float: right; height: 25px;"></div>
          </div>
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="queryInput">
          </el-input>
          <el-card v-loading="notLoading" shadow="never" style=" margin-top: 10px ;">
            <div style="height: 460px;overflow:auto" @dragenter="notContentDragenter('1')">
              <transition-group
                name="drag-not"
                class="list"
                tag="ul"
                v-show="notList.length > 0"
              >
                <li
                  @dragenter="notDragenter($event, index , item)"
                  @dragover="notDragover($event, index , item)"
                  @dragstart="notDragstart(index , item)"
                  draggable = true
                  v-for="(item, index) in notList"
                  :key="item.operationCode"
                  class="not-list-item">
                  {{item.operationCode}}
                </li>
              </transition-group>
              <el-empty v-show="notList.length == 0" description="移除工序拖拽到此处"></el-empty>
            </div>
          </el-card>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-row :gutter="12">
          <el-col :span="24">
            <el-card >
              <div slot="header" class="clearfix">
                <span>工艺路线</span>

                <el-button @click="submintFrom" style="float: right; padding-right: 20px;height: 25px;width: 100px" type="success" size="mini">
                  <i class="el-icon-check"></i>
                  保存
                </el-button>
              </div>
              <el-descriptions v-loading="pathLoading" :column="4" size="medium">
                <el-descriptions-item label="路线编号">{{craftPath.pathCode}}</el-descriptions-item>
                <el-descriptions-item label="路线名称">{{craftPath.pathName}}</el-descriptions-item>
                <el-descriptions-item label="产品编码">{{craftPath.productCode}}</el-descriptions-item>
                <el-descriptions-item label="版本">{{craftPath.version}}</el-descriptions-item>
                <el-descriptions-item label="是否禁用">
                  <el-tag type="success" size="small" v-if="craftPath.isDisable == '0'">{{dict.label.is_disable[craftPath.isDisable]}}</el-tag>
                  <el-tag type="info" size="small" v-if="craftPath.isDisable == '1'">{{dict.label.is_disable[craftPath.isDisable]}}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="创建人">{{craftPath.createBy}}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{craftPath.createTime}}</el-descriptions-item>
                <el-descriptions-item label="更新人">{{craftPath.updateBy}}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{craftPath.updateTime}}</el-descriptions-item>
                <el-descriptions-item label="备注">{{craftPath.remark}}</el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="12" style="padding-top: 15px">
          <el-col :span="24">
            <el-card>
              <el-card v-loading="checkedLoading" shadow="never">
                <div style="height: 345px;" @dragenter="checkedContentDragenter('2')">
                  <transition-group
                    name="drag-not"
                    class="checked-list"
                    tag="ul"
                  >
                    <li v-show="checkedList.length > 0"
                      @dragenter="checkedDragenter($event, index , item)"
                      @dragover="checkedDragover($event, index , item)"
                      @dragstart="checkedDragstart(index , item)"
                      @dblclick="checkedDblclick(index , item)"
                      draggable = true
                      v-for="(item, index) in checkedList"
                      :key="item.operationCode"
                      class="checked-list-item">
                      <div class="checked-item-content">
                        {{item.operationName}}
                      </div>
                      <div class="checked-item-ico">
                        <i class="el-icon-arrow-right"></i>
                      </div>
                    </li>
                  </transition-group>
                  <el-empty v-show="checkedList.length == 0" description="拖拽左侧工序到此处"></el-empty>
                </div>
              </el-card>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>


    <el-dialog  :visible.sync="formStatus" title="编辑工序" width="500px">
      <el-form ref="form" :model="editDetail" :rules="rules" size="small" label-width="80px">
        <el-form-item label="工序编号">
          <el-input :disabled="true" v-model="editDetail.operationCode" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="工序名称">
          <el-input :disabled="true" v-model="editDetail.operationName" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="是否校验">
          <el-radio-group v-model="editDetail.isCheck">
            <el-radio  v-for="item in dict.whether"  :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否屏蔽">
          <el-radio-group v-model="editDetail.isShield">
            <el-radio  v-for="item in dict.whether" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="formStatus = false">取消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="confirmEdit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudCraftPathDetail from '@/api/craft/craftPathDetail'
import crudCraftOperationProduct from '@/api/craft/craftOperationProduct'
import crudCraftPath from '@/api/craft/craftPath'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = { id: null, pathId: null, operationCode: null, operationName: null, executionOrder: null, upStationCode: null, nextStationCode: null, isCheck: null, isShield: null, remark: null, createBy: null, createTime: null, updateBy: null, updateTime: null }
export default {
  name: 'CraftPathDetail',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['is_disable','whether'],
  cruds() {
    return CRUD({
      title: '工艺路线详情',
      url: 'api/craftPathDetail',
      idField: 'id',
      sort: 'id,desc',
      queryOnPresenterCreated: false,
      crudMethod: { ...crudCraftPathDetail }})
  },
  data() {
    return {
      pid: 0,
      craftPath: {},
      editDetail: {},
      dblclickIndex: '',
      formStatus: false,
      queryInput: '',
      dragType: '',
      notList: [],
      notIndex: '',
      checkedList: [],
      checkedIndex: '',
      notLoading: false,
      checkedLoading: false,
      pathLoading: false,
      submitLoading: false,
      permission: {
        add: ['admin', 'craftPathDetail:add'],
        edit: ['admin', 'craftPathDetail:edit'],
        del: ['admin', 'craftPathDetail:del']
      },
      rules: {
      },
      queryTypeOptions: [
        { key: 'id', display_name: 'ID' },
        { key: 'pathId', display_name: '路线ID' },
        { key: 'operationCode', display_name: '工序编号' },
        { key: 'operationName', display_name: '工序名称' },
        { key: 'executionOrder', display_name: '执行顺序' },
        { key: 'upStationCode', display_name: '上工序编号' },
        { key: 'nextStationCode', display_name: '下工序编号' },
        { key: 'isCheck', display_name: '是否校验' },
        { key: 'isShield', display_name: '是否屏蔽' },
        { key: 'remark', display_name: '描述' },
        { key: 'createBy', display_name: '创建人' },
        { key: 'updateBy', display_name: '更新人' }
      ]
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    //提交
    submintFrom(){
      if(this.checkedList.length == 0){
        this.$notify.error({
          title: '错误',
          message: '工艺路线不能为空，请拖拽配置！'
        });
        return false;
      }
      //组装数据
      const arrays = [];
      let upStationCode , nextStationCode;
      for (let i = 0; i < this.checkedList.length; i++) {
        let checked = this.checkedList[i];
        if(i > 0){
          upStationCode = this.checkedList[i -1].operationCode;
        }
        if(i != this.checkedList.length -1){
          nextStationCode = this.checkedList[i + 1].operationCode
        } else {
          nextStationCode = null;
        }
        const path = {
          pathId: this.pid,
          operationCode: checked.operationCode,
          operationName: checked.operationName,
          executionOrder: i,
          upStationCode: upStationCode,
          nextStationCode: nextStationCode,
          isCheck: checked.isCheck ? checked.isCheck : '1',
          isShield: checked.isShield ? checked.isShield : '0',
          remark: checked.remark
        }
        arrays.push(path);
      }

      this.checkedLoading = true;
      crudCraftPathDetail.addBatch(arrays).then(res =>{
        this.checkedLoading = false;
        this.$notify({
          title: '成功',
          message: '保存成功！',
          type: 'success'
        });
      })
    },
    //双击打开编辑
    checkedDblclick(index , item){
      this.dblclickIndex = index;
      this.editDetail = {
        operationCode: item.operationCode,
        operationName: item.operationName,
        isCheck: item.isCheck ? item.isCheck : '1',
        isShield: item.isShield ? item.isShield : '0'
      };
      this.formStatus = true;
    },
    //确认编辑
    confirmEdit(){
      let checked = this.checkedList[this.dblclickIndex];
      checked.isCheck = this.editDetail.isCheck;
      checked.isShield = this.editDetail.isShield;
      this.formStatus = false;
    },
    notDragstart(index , item) {
      this.dragType = item.dragType;
      this.notIndex = index;
    },
    checkedDragstart(index , item) {
      this.dragType = item.dragType;
      this.checkedIndex = index;
    },
    notDragover(e, index, item) {
      e.preventDefault();
    },
    checkedDragover(e, index, item) {
      e.preventDefault();
    },
    notDragenter(e, index,item) {
      e.preventDefault();
      // 避免源对象触发自身的dragenter事件
      if (this.notIndex !== index && this.dragType == item.dragType ) {
        const moving = this.notList[this.notIndex];
        this.notList.splice(this.notIndex, 1);
        this.notList.splice(index, 0, moving);
        // 排序变化后目标对象的索引变成源对象的索引
        this.notIndex = index;
      }
    },
    checkedDragenter(e, index,item) {
      e.preventDefault();
      // 避免源对象触发自身的dragenter事件
      if (this.checkedIndex !== index && this.dragType == item.dragType) {
        const moving = this.checkedList[this.checkedIndex];
        this.checkedList.splice(this.checkedIndex, 1);
        this.checkedList.splice(index, 0, moving);
        // 排序变化后目标对象的索引变成源对象的索引
        this.checkedIndex = index;
      }
    },
    notContentDragenter(dragType){
      if(this.dragType != dragType){
        const moving = this.checkedList[this.checkedIndex];
        this.dragType = dragType;
        moving.dragType = dragType;
        this.checkedList.splice(this.checkedIndex, 1);
        this.notList.splice(0, 0, moving);
        this.notIndex = 0;
      }
    },
    checkedContentDragenter(dragType){
      console.log(dragType)
      if(this.dragType != dragType){
        const moving = this.notList[this.notIndex];
        this.dragType = dragType;
        moving.dragType = dragType;
        this.notList.splice(this.notIndex, 1);
        this.checkedList.splice(0, 0, moving);
        this.checkedIndex = 0;
      }
    },
    setNotList(checkedList , notList){
      if(!checkedList || checkedList.length == 0){
        this.notList = notList;
        return ;
      }
      const indexs = [];
      //匹配已选择的
      for (let i = 0; i < notList.length; i++) {
        let adds = true;
        for (let j = 0; j < checkedList.length; j++) {
          if(notList[i].operationCode == checkedList[j].operationCode){
            adds = false;
            break;
          }
        }
        if(adds){
          indexs.push(notList[i]);
        }
      }
      this.notList = indexs;
    },
    async initData(){
      this.pathLoading = true;
      this.notLoading = true;
      this.checkedLoading = true;
      //得到页面传递过来的id
      this.pid = this.$route.params.id
      await crudCraftPath.getById({id:this.pid}).then(res => {
        this.pathLoading = false;
        this.craftPath = res;
      });

      //查询已经选择的工序列表
      await crudCraftPathDetail.list({pathId:this.pid}).then(res => {
        this.checkedLoading = false;
        if(res && res.length > 0){
          for (const checked of res) {
            checked.dragType = '2';
          }
          this.checkedList = res;
        } else {
          this.checkedList = [];
        }
      });
      //查询工序列表
      await  crudCraftOperationProduct.getByProduct({ productCode: this.craftPath.productCode }).then(res => {
        this.notLoading = false;
        if(res && res.length > 0){
          for (const not of res) {
            not.dragType = '1';
          }
          this.setNotList(this.checkedList,res);
        }else{
          this.notList = [];
        }
      });
    }
  },
  mounted() {
    this.initData();
  }
}
</script>

<style lang="scss" scoped>

  .list {
    list-style:none;
    margin:0;
    padding:0;
  }
  .checked-list {
    list-style:none;
    margin:0;
    padding:0;
  }

  .drag-not-move {
    transition: transform .5s;
  }

  .drag-checked-move {
    transition: transform .5s;
  }

  .not-list-item {
    cursor: move;
    width: 100%;
    border-radius: 4px;
    margin-bottom: 10px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    color: #409eff;
    background: #ecf5ff;
    border: 1px solid #b3d8ff;
  }




  .checked-list-item {
    cursor: move;
    list-style:none;
    float: left; /* 往左浮动 */
    display: block;
    width: 130px;
    margin-bottom: 20px;
  }


  .checked-item-content {
    height: 50px;
    line-height: 50px;
    text-align: center;
    border-radius: 4px;
    width: 90px;
    float: left;
    color: #409eff;
    background: #ecf5ff;
    border: 1px solid #b3d8ff;
  }


  .checked-item-ico {
    text-align: center;
    height: 50px;
    line-height: 50px;
    width: 40px;
    color: #b3d8ff;
    float: right;
  }

  .checked-item-ico i{
    font-weight: bold;
  }

  .checked-list li:last-of-type .checked-item-ico{
    display:none;
  }

</style>

